package com.huizu.project.apiController;


import com.huizu.common.annotation.Anonymous;
import com.huizu.common.config.RuoYiConfig;
import com.huizu.common.core.domain.AjaxResult;
import com.huizu.common.core.redis.RedisCache;
import com.huizu.common.exception.ServiceException;
import com.huizu.common.utils.OssUtil;
import com.huizu.common.utils.ServletUtils;
import com.huizu.common.utils.dx.MessageUtils;
import com.huizu.common.utils.file.FileUploadUtils;
import com.huizu.common.utils.file.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Anonymous
@RestController
@RequestMapping("/api/utils")
public class ApiProUtilsController {

    @Autowired
    private RedisCache redisCache;


    @PostMapping("/ossUpload2")
    public AjaxResult upload(MultipartFile file) throws IOException {

        if (isImage(file)){
            // 文件不大于100M
            boolean m = checkFileSize(file.getSize(), 5, "M");
            if (!m)
                return AjaxResult.error("上传图片大小不能超过5MB,请尝试压缩后上传");
        }else if (isVideo(file)){
            // 文件不大于100M
            boolean m = checkFileSize(file.getSize(), 20, "M");
            if (!m)
                return AjaxResult.error("上传视频大小不能超过20mb,请尝试压缩后上传");
        }else {
            // 文件不大于100M
            boolean m = checkFileSize(file.getSize(), 50, "M");
            if (!m)
                return AjaxResult.error("上传大小不能超过50mb,请尝试压缩后上传");
        }

        String s = OssUtil.uploadIimage(file);//文件上传的地址
        Map<String,Object> map = new HashMap<>();
        map.put("url", s);//图片路径
        map.put("fileName",s);
        map.put("newFileName", FileUtils.getName(s));
        map.put("originalFilename", file.getOriginalFilename());
        return AjaxResult.success(map);
    }

    @PostMapping("/ossUpload")
    public AjaxResult uploadIImage2(@RequestBody MultipartFile file) throws IOException {
        try
        {
            AjaxResult ajax = AjaxResult.success();
            String originalFilename= file.getOriginalFilename();
            ajax.put("originalFilename", originalFilename);
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
//          String url = RuoYiConfig.getBaseUrl() + fileName;
            ajax.put("url", fileName);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));

            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取验证码
     * @param map
     * @return
     */
    @PostMapping("/getVerificationCode")
    public AjaxResult getCode(@RequestBody Map<String,Object> map){
        if (map.get("phone")==null)
            throw new ServiceException("手机号不能为空");
        String phone = String.valueOf(map.get("phone"));
        Map<String, Object> message = MessageUtils.getMessage(map);
        if (message.get("message")==null){
            throw new ServiceException("验证码发送失败，请重试");
        }
        redisCache.setCacheObject(phone,message.get("message"),1600, TimeUnit.SECONDS);
        return AjaxResult.success("发送成功");
    }


    /**
     * 获取完整的请求路径，包括：域名，端口，上下文访问路径
     *
     * @return 服务地址
     */
    public String getUrl()
    {
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }

    public static String getDomain(HttpServletRequest request)
    {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();

        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    private static boolean isVideo(MultipartFile file) {
        String fileExtension = getFileExtension(file.getOriginalFilename());
        if ("mp4".equals(fileExtension)||"avi".equals(fileExtension)||"mov".equals(fileExtension))
            return true;
        return false;
    }

    private static boolean isImage(MultipartFile file) {
        String fileExtension = getFileExtension(file.getOriginalFilename());
        if ("png".equals(fileExtension)||"jpg".equals(fileExtension)||"gif".equals(fileExtension))
            return true;
        return false;
    }

    public static String getFileExtension(String filename) {
        if (filename != null && !filename.isEmpty()) {
            int dotIndex = filename.lastIndexOf(".");
            if (dotIndex > 0 && dotIndex < filename.length() - 1) {
                return filename.substring(dotIndex + 1);
            }
        }
        return "";
    }

    /**
     * 判断文件大小
     *
     * @param len
     *            文件长度
     * @param size
     *            限制大小
     * @param unit
     *            限制单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(Long len, int size, String unit) {
//        long len = file.length();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }


}
